<template>
  <page-layout>
    <div class="login-box">
    <div v-if="showLogin" class="login-page">
      <div class="phone">
        <input
          type="text"
          v-model="loginObj.phone"
          placeholder="请输入手机号"
        />
      </div>
      <div class="phone">
        <input type="text" v-model="loginObj.vdtCode" placeholder="请输验证码" />
        <span class="vcode" @click="getVdtCode">{{ vCodeText }}</span>
      </div>

      <van-checkbox icon-size="18px" v-model="remember" checked-color="#ee0a24">记住手机号</van-checkbox
      >
      <van-checkbox icon-size="18px" v-model="auto" checked-color="#ee0a24">7天免登录</van-checkbox
      >
      <van-button color="#7232dd" type="primary" block @click.native="loginEvt">登录</van-button>
    </div>
    <div v-else class="welcom-page">
      <van-circle
        size="40px"
        @click.native="endTimer"
        :clockwise="false"
        v-model="currentRate"
        :rate="100"
        color="#f99"
        :text="Math.ceil(currentRate / 20) + 's'"
      />
      <div class="title">美少女智能采购系统</div>
      <div class="month-text">{{ monthText }}</div>
    </div>
    <span class="footer">meishaonvzhanshi &copy; chenjuan</span>
  </div>
  </page-layout>
</template>

<script>
import { getCodeApi, loginApi, userInfoApi, autoLoginApi } from "../../apis/loginApis";
import {AES, enc} from 'crypto-js'
export default {
  data() {
    return {
      showLogin: false, //展示欢迎还是登陆
      currentRate: 100, 
      vCodeText: "获取验证码",
      remember: false,  //是否记住手机号
      auto: false,  //是否自动登录
      monthText: [
        "一月，我听到了爆竹的声声催促",
        "二月，我闻到了腊梅的缕缕幽香",
        "三月，我看到了桃花绚烂如云霞",
        "四月，我躺在了柳阴中酣然入梦",
        "五月，我品尝着晶莹剔透的樱桃",
        "六月，我观赏水莲花的绰约芳姿",
        "七月，我跃入那清波荡漾的碧水",
        "八月，置身于桂花雨中翩然起舞",
        "九月，我漫步在飘满落叶的小径",
        "十月，我欣然采摘那累累的硕果",
        "十一月，我聆听冬天走来的步履",
        "十二月，我掬起一捧洁白的雪花",
      ][new Date().getMonth()],
      loginState: "login",  //登录状态 loading-接口还在请求，login-登录页面，home-自动登录
      timer: null,
      loginObj: {
        phone: '13611660036',
        vdtCode: '',
      },
      vdtTime: 60,
    };
  },
  created() {
    this.currentRateChang();
    this.autoLogin()
  },

  methods: {
    //登录方法
    async loginEvt() {
      if (!/^[1][3-9]{1}[0-9]{9}$/.test(this.loginObj.phone)) {
        this.$toast("请正确输入手机号");
        return;
      }

      if (!/[0-9]{4}/.test(this.loginObj.vdtCode)) {
        // console.log('验证码错误')
        this.$toast("验证码错误");
        return;
      }
      //数据接口调用
      this.$toast.loading({
        message: "登录中...",
        forbidClick: true,
        duration: 0,
      });

      let result = await loginApi(this.loginObj)
      if (result.code !== 200) {
        this.$toast("登陆失败，请重试！");
        this.$toast.clear()
        return;
      }

      //获取用户信息
      //用户信息接口需要使用token
      this.$store.commit('common/setToken', result.data.token)
      let userinfo = await userInfoApi(result.data.id)
      // console.log('userinfo',userinfo)
      //将用户信息存入store
      this.$store.commit('common/setUser',userinfo.data)
      //判断是否记住手机号
      if(this.remember){
        localStorage.setItem('user-phone',AES.encrypt(this.loginObj.phone,'asdfg').toString())
      }else{
        localStorage.removeItem('user-phone')
      }
      //判断是否自动登录
      if(this.auto){
        localStorage.setItem('auto-token',result.data.token)
      }else{
        localStorage.removeItem('auto-token')
      }

      this.$toast.clear()
      this.$store.dispatch('common/rightsAct', userinfo.data.role)
      // console.log('userinfo.data.role',userinfo.data.role)
      // console.log('this.$store',this.$store)
      // debugger;
      this.$router.push('/home')
    
    },
      
    async getVdtCode() {
      if (this.vCodeText !== "获取验证码") return;
      //判断手机号是否合理
      if (!/^[1][3-9]{1}[0-9]{9}$/.test(this.loginObj.phone)) {
        this.$toast({ message: "电话号码错误", position: "bottom" });
        return;
      }
      this.vCodeText = "获取中...";

      //发送请求
      let result = await getCodeApi(this.loginObj.phone);
      // console.log(result);
      if (result.code !== 200) {
        this.$toast({
          message: "获取验证码失败",
          position: "bottom",
        });
        this.vCodeText = "获取验证码";
        return;
      }
      this.$toast.success(`验证码：${result.data.vdtCode}`);
      // debugger;
      this.vdtTimeCount(Date.now());
    },

    //获取验证码按钮时间倒计时
    vdtTimeCount(st) {
      // debugger;
      setTimeout(() => {
        let passTime = 60 - Math.ceil((Date.now() - st) / 1000);
        if (passTime > 0) {
          this.vCodeText = "重新获取" + passTime + "s";
          this.vdtTimeCount(st);
        }
        if (passTime <= 0) {
          this.vCodeText = "获取验证码";
        }
      }, 200);
    },

    endTimer() {
      if (this.loginState == "loading") return;
      if (this.loginState == "home") {
        this.$router.push("/home");
      }else{
        this.showLogin = true;
      }
      clearTimeout(this.timer);
    },

    currentRateChang() {
      this.timer = setTimeout(() => {
        this.currentRate -= 1;
        if (this.currentRate > 0) {
          this.currentRateChang();
        }else{
          this.endTimer()
        }
      }, (1000 * 5) / 100);
    },

    //判断登录状态，未登录-login 记住手机号-login 免登录-home
    async autoLogin() {
      //获取token进行判断
      let autoTokenFlag = localStorage.getItem("auto-token");
      if (!!autoTokenFlag) {
        this.$store.commit("common/setToken", autoTokenFlag);
        //发送请求
        let result = await autoLoginApi()
        console.log('auto result',result)
        if(result.code === 200){
          this.$store.commit('common/setUser',result.data)
          this.loginState = 'home'
        }else{  //判断是否记住手机号
          this.isRememberPhone()
        }

      } else {
        //不存在token，判断一下是否保存了手机号
        this.isRememberPhone()
      }
    },
    //判断是否记住手机号
    isRememberPhone(){
      let rememberPhone = localStorage.getItem('user-phone')
      if(!!rememberPhone){
        this.loginObj.phone = AES.decrypt(rememberPhone,'asdfg').toString(enc.Utf8)
        this.remember = true
      }
      this.loginState = 'login'
    }
  },
  
};
</script>

<style lang="less" scoped>
@import "./index.less";
</style>